package com.cmxh.cloundnote.Controller;

import com.alibaba.excel.EasyExcel;
import com.cmxh.cloundnote.pojo.Article;
import com.cmxh.cloundnote.service.ArticleService;
import com.cmxh.cloundnote.util.Code;
import com.cmxh.cloundnote.util.PageUtil;
import com.cmxh.cloundnote.util.Result;
import com.cmxh.cloundnote.util.UserListener;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @RequestMapping("/findAll")
    public Result findAll(@RequestBody PageUtil pageUtils) {
        System.out.println(pageUtils);
        PageInfo<Article> list = articleService.findAll(pageUtils);
        System.out.println(list);
        if (list != null){
            return new Result(Code.GET_OK,list,"查询成功");
        }else {
            return new Result(Code.GET_ERR,"查询失败");
        }
    }
    @RequestMapping("/deleted/{id}")
    public Result deleted(@PathVariable Integer id) {
        int i = articleService.deleted(id);
        if (i>0){
            return new Result(Code.UPDATE_OK,"删除成功");
        }else {
            return new Result(Code.UPDATE_ERR,"删除失败");
        }
    }
    @Autowired
    private UserListener ul;
    @PostMapping(value = "/importData")
    public Result importData(MultipartFile file){
        try {
            // 获取前端上传文件的字节流  读流
            InputStream inputStream = file.getInputStream();
            // 从这个文件流中读取数据并且把这一行数据封装成文章对象  并且把这7个文章对象存放到一个集合中
            /**
             * 第一个参数 客户端的读流
             * 第二个参数 我们需要把excel中每一行封装成什么对象  你就写Article类
             *
             * sheet(0)  读取第一个工作表的数据
             * .doReadSync()  异步读取
             */
            List<Article> list= EasyExcel.read(inputStream)
                    .registerReadListener(ul).
                    head(Article.class)
                    .sheet("学生").doReadSync();
            if(list.size()>0){
                System.out.println(list);
            }

            return new Result(Code.IMPORT_OK,"导入成功");

        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Code.IMPORT_ERR,"导入失败");
        }
    }
/**导出**/



}
